package br.com.sistema.util;

import br.com.sistema.infraestrutura.CFG;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/*
To use this program, change values for the following three constants,

SMTP_HOST_NAME -- Has your SMTP Host Name
SMTP_AUTH_USER -- Has your SMTP Authentication UserName
SMTP_AUTH_PWD  -- Has your SMTP Authentication Password

Next change values for fields

emailMsgTxt  -- Message Text for the Email
emailSubjectTxt  -- Subject for email
emailFromAddress -- Email Address whose name will appears as "from" address

Next change value for "emailList".
This String array has List of all Email Addresses to Email Email needs to be sent to.


Next to run the program, execute it as follows,

SendMailUsingAuthentication authProg = new SendMailUsingAuthentication();

 */
public class MailSender {

    public void enviarEmail(String destinatarios[], String assunto,
            String mensagem, String remetente) throws MessagingException {
        boolean debug = false;

        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.transport.protocol", "smtp"); //define protocolo de envio como SMTP  
        props.put("mail.smtp.starttls.enable","true");   
        props.put("mail.smtp.host", CFG.SMTP_HOST_NAME); //server SMTP do GMAIL  
        props.put("mail.smtp.auth", "true"); //ativa autenticacao  
        props.put("mail.smtp.user", CFG.SMTP_AUTH_USER); //usuario ou seja, a conta que esta enviando o email (tem que ser do GMAIL)  
        props.put("mail.debug", "true");
        props.put("mail.smtp.port", CFG.SMTP_PORT); //porta  
        props.put("mail.smtp.socketFactory.port", CFG.SMTP_PORT); //mesma porta para o socket  
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  
        props.put("mail.smtp.socketFactory.fallback", "false");  
        props.put("mail.smtp.auth", "true");

        Authenticator auth = new SMTPAuthenticator();
        Session session = Session.getDefaultInstance(props, auth);

        session.setDebug(debug);

        // create a message
        Message msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom = new InternetAddress(remetente);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[destinatarios.length];
        for (int i = 0; i < destinatarios.length; i++) {
            addressTo[i] = new InternetAddress(destinatarios[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);


        // Setting the Subject and Content Type
        msg.setSubject(assunto);
        msg.setContent(mensagem, "text/html; charset=utf-8");
        
        
        //Objeto encarregado de enviar os dados para o email  
        Transport tr;  
        try {  
            tr = session.getTransport("smtp"); //define smtp para transporte  
            /* 
             *  1 - define o servidor smtp 
             *  2 - seu nome de usuario do gmail 
             *  3 - sua senha do gmail 
             */  
            tr.connect(CFG.SMTP_HOST_NAME, CFG.SMTP_AUTH_USER, CFG.SMTP_AUTH_PWD);  
            msg.saveChanges(); // don't forget this  
            //envio da mensagem  
            tr.sendMessage(msg, msg.getAllRecipients());  
            tr.close();  
        } catch (Exception e) {  
            // TODO Auto-generated catch block  
            System.out.println(">> Erro: Envio Mensagem");  
            e.printStackTrace();  
        }
        //Transport.send(msg);
    }

    /**
     * SimpleAuthenticator is used to do simple authentication
     * when the SMTP server requires it.
     */
    private class SMTPAuthenticator extends javax.mail.Authenticator {

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            String username = CFG.SMTP_AUTH_USER;
            String password = CFG.SMTP_AUTH_PWD;
            return new PasswordAuthentication(username, password);
        }
    }
//    public static void main(String[] args) {
//        Comunicacao c = new Comunicacao();
//        Query q = new Query();
//        try{
//        Usuario u = q.getUsuario("00569072140");
//        c.enviarEmail(new String[]{u.getEmail()}, "Recuperação de Senha", "Sua senha é: "+u.getSenha(), "EADmin - CIAR, UFG");
//        }catch(MessagingException ex){
//            System.out.println(ex);
//        }catch(java.text.ParseException ex){
//            System.out.println(ex);
//        }catch(SQLException ex){
//
//            System.out.println(ex);
//        }
//    }

}
